<template>
  <view class="chat-container">
    <!-- 顶部搜索和订阅区域 -->
    <view class="top-section">
      <view class="search-bar">
        抓住AI风口,抢占人生先机
      </view>
      <!-- <view class="subscribe-btn" @click="goToRecharge">
        <text class="subscribe-icon">+</text>
        <text class="subscribe-text">订阅</text>
      </view> -->
    </view>
    
    <!-- 主要内容区域 -->
      <scroll-view 
        class="content-scroll" 
        scroll-y="true"
        @scrolltolower="loadMore"
      >
        <!-- <view class="category-section">
          <view class="category-header" @click="toggleCategory('assistant')">
            <view class="category-title">
              <text class="toggle-icon">{{ categories.assistant.expanded ? '▼' : '►' }}</text>
              <text class="category-name">我的收藏</text>
            </view>
            <text class="category-count">{{ categories.assistant.count }}</text>
          </view>
          
          <view class="category-content" v-if="categories.assistant.expanded">
            <view 
              class="chat-item" 
              v-for="item in categories.assistant.items" 
              :key="item.id"
              @click="goToChatDetail(item)"
            >
              <view class="item-icon">
                <image 
                  :src="item.coverUrl" 
                  class="icon-image" 
                  mode="aspectFit"
                  @error="handleImageError"
                ></image>
              </view>
              <view class="item-info">
                <text class="item-title">{{ item.name|| '未命名应用' }}</text>
                <text class="item-desc">{{ item.description || item.desc || '暂无描述' }}</text>
              </view>
            </view>
          </view>
        </view> -->
        
        <!-- API分类区域 -->
            <!-- 分类列表 -->
            <view 
              v-for="category in categories.categoriesList.items" 
              :key="category.id"
              class="category-section"
            >
              <view class="category-header" @click="toggleCategoryApps(category)">
                <view class="category-title">
                  <text class="toggle-icon">{{ categories.categoriesList.apps[category.id]?.expanded ? '▼' : '►' }}</text>
                  <text class="category-name">{{ category.name || '未命名分类' }}</text>
                </view>
                <!-- <text class="category-count">{{ categories.categoriesList.apps[category.id]?.items?.length || 0 }}</text> -->
              </view>
              
              <!-- 分类下的应用列表 -->
              <view v-if="categories.categoriesList.apps[category.id]?.expanded" >
                
                <view 
                  class="chat-item"
                  v-for="app in categories.categoriesList.apps[category.id]?.items || []" 
                  :key="app.id"
                  @click.stop="goToChatDetail(app)"
                >
                  <view class="item-icon">
                    <image 
                      :src="app.coverUrl" 
                      class="icon-image" 
                      mode="aspectFit"
                      @error="handleImageError"
                    ></image>
                  </view>
                  <view class="item-info">
                    <text class="item-title">{{ app.name|| '未命名应用' }}</text>
                    <text class="item-desc">{{ app.description || app.desc || '暂无描述' }}</text>
                  </view>
                </view>
              </view>
            </view>
            
            <!-- 空状态 -->
            <view class="empty-state" v-if="!categories.categoriesList.loading && categories.categoriesList.items.length === 0">
              <text class="empty-text">暂无分类数据</text>
            </view>

      
      <!-- 加载更多提示 -->
      <view class="load-more" v-if="loading">
        <text class="load-text">加载中...</text>
      </view>
      
      <!-- 没有更多数据提示 -->
      <view class="load-more" v-if="!loading && !hasMore && categories.assistant.items.length > 0">
        <text class="load-text">已加载全部内容</text>
      </view>
      
      <!-- 空状态提示 -->
      <!-- <view class="empty-state" v-if="!loading && categories.assistant.items.length === 0">
        <text class="empty-text">暂无收藏内容，快去AI市场添加收藏吧</text>
      </view> -->
    </scroll-view>
  </view>
</template>

<script>
import { userAPI } from '../../utils/api.js'

export default {
  data() {
    return {
      loading: false,
      hasMore: true,
      page: 1,
      pageSize: 30,
      categories: {
        assistant: {
          expanded: true,
          count: 0,
          items: []
        },
        categoriesList: {
          expanded: false,
          count: 0,
          items: [],
          apps: {},
          loading: false
        },
		isMember:uni.getStorageSync('isMember'),
        chat: {
          expanded: true,
          count: 9,
          items: [
            {
              id: 3,
              title: 'Chat GPT 4.0',
              description: '最好用的AI软件',
              icon: '/static/icons/gpt.png'
            },
            {
              id: 4,
              title: 'AI聊天3.5',
              description: '智能AI助手',
              icon: '/static/icons/ai-chat.png'
            },
            {
              id: 5,
              title: 'DeepSeek V3',
              description: '全球最强大的开源模型',
              icon: '/static/icons/deepseek.png'
            },
            {
              id: 6,
              title: 'DeepSeek R1',
              description: '全球最强大的开源模型',
              icon: '/static/icons/deepseek.png'
            },
            {
              id: 7,
              title: '文章改写',
              description: '文章改写大师',
              icon: '/static/icons/rewrite.png'
            },
            {
              id: 8,
              title: '文章续写',
              description: '续写和扩写各种文章',
              icon: '/static/icons/continue.png'
            },
            {
              id: 9,
              title: '智能AI大师',
              description: '智能AI强者',
              icon: '/static/icons/ai-master.png'
            },
            {
              id: 10,
              title: '文档上传分析',
              description: '支持doc文档上传分析',
              icon: '/static/icons/document.png'
            },
            {
              id: 11,
              title: '文心一言',
              description: '百度自行研发的大语言模型.',
              icon: '/static/icons/wenxin.png'
            }
          ]
        },
        writing: {
          expanded: false,
          count: 9,
          items: []
        },
        painting: {
          expanded: false,
          count: 6,
          items: []
        }
      }
    }
  },
  
  onLoad(options) {
    if (options && options.ref) {
      // 如果有ref参数，存储到缓存中
      uni.setStorageSync('referralCode', options.ref)
    } else {
      // 如果没有ref参数，清除缓存
      uni.removeStorageSync('referralCode')
    }
	
  },
  onShow(){
	uni.showLoading()
	setTimeout(()=>{
		// 获取收藏列表
		// this.getFavoriteList()
		// 获取分类列表
		this.getCategoryList()
		uni.hideLoading()
	},300)
  },
  
  methods: {
    // 检查登录状态
    checkLoginStatus() {
      const token = uni.getStorageSync('token')
      if (!token) {
        uni.reLaunch({
          url: '/pages/login/login'
        })
      }
    },
    
    // 切换分类展开/收起
    toggleCategory(categoryKey) {
      this.categories[categoryKey].expanded = !this.categories[categoryKey].expanded
    },
    
    // 切换分类下的应用展开/收起
    async toggleCategoryApps(category) {
      const categoryId = category.id
      
      // 如果分类下没有应用数据或未展开，则获取数据
      if (!this.categories.categoriesList.apps[categoryId] || !this.categories.categoriesList.apps[categoryId].expanded) {
        // 初始化分类应用数据
        if (!this.categories.categoriesList.apps[categoryId]) {
          this.$set(this.categories.categoriesList.apps, categoryId, {
            expanded: true,
            items: [],
            loading: false
          })
        } else {
          this.categories.categoriesList.apps[categoryId].expanded = true
        }
        
        // 获取分类下的应用列表
        await this.getCategoryApps(categoryId)
      } else {
        // 收起分类下的应用
        this.categories.categoriesList.apps[categoryId].expanded = false
      }
    },
    
    // 获取分类列表
    async getCategoryList() {
		
      try {
        this.categories.categoriesList.loading = true
        
        const result = await userAPI.categoryList()
        
        if (result.code === 0) {
          const categoryList = result.data?.list || result.list || []
          this.categories.categoriesList.items = categoryList
          this.categories.categoriesList.count = result.data?.total || result.total || 0
		  const token = uni.getStorageSync('token')
		  
		  const memberRes = await userAPI.getMemberInfo({
			  Authorization :`Bearer ${token}`
		  })
		  this.isMember=memberRes?.data?.memberId
		  uni.setStorageSync('isMember',this.isMember)
		  
        } else {
          uni.showToast({
            title: result.message || '获取分类列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取分类列表失败:', error)
      } finally {
        this.categories.categoriesList.loading = false
      }
    },
    
    // 获取分类下的应用列表
    async getCategoryApps(categoryId) {
      try {
        // 确保分类应用数据存在
        if (!this.categories.categoriesList.apps[categoryId]) {
          this.$set(this.categories.categoriesList.apps, categoryId, {
            expanded: true,
            items: [],
            loading: true
          })
        } else {
          this.categories.categoriesList.apps[categoryId].loading = true
        }
        
        const params = {
          page: this.page,
          pageSize: this.pageSize,
          categoryId: categoryId
        }
        
        const result = await userAPI.appList(params)
        
        if (result.code === 0) {
          const appList = result.data?.list || result.list || []
          this.categories.categoriesList.apps[categoryId].items = appList
        } else {
          uni.showToast({
            title: result.message || '获取应用列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取应用列表失败:', error)
        uni.showToast({
          title: '获取应用列表失败',
          icon: 'none'
        })
      } finally {
        if (this.categories.categoriesList.apps[categoryId]) {
          this.categories.categoriesList.apps[categoryId].loading = false
        }
      }
    },
    
    // 跳转到对话详情页
    goToChatDetail(item) {
		if(!this.isMember&&item.type=='agent'){
			uni.showModal({
				title:'非会员不能使用哦～',
				content:'快去升级成为会员吧',
				confirmText:'开通会员',
				success(res) {
					if(res.confirm){
						uni.navigateTo({
						  url: `/pages/recharge/recharge`
						})
					}
				}
			})
			return
		}
      uni.navigateTo({
        url: `/pages/chat-detail/chat-detail?id=${item.id}&title=${item.name}&type=${item.type}&categoryId=${item.categoryId}&outputType=${item.outputType}`
      })
    },
    
    // 跳转到充值页面
    goToRecharge() {
      uni.navigateTo({
        url: '/pages/recharge/recharge'
      })
    },
    
    // 获取收藏列表
    async getFavoriteList(isLoadMore = false) {
      if (this.loading) return
      
      try {
        this.loading = true
        
        const params = {
          page: this.page,
          pageSize: this.pageSize
        }
        //const result = await userAPI.categoryList(params)
        const result = await userAPI.getFavoriteList(params)
        
        if (result.code === 0) {
          const favoriteList = result.data?.list || result.list || []
          
          if (isLoadMore) {
            // 加载更多，追加数据
            this.categories.assistant.items = [...this.categories.assistant.items, ...favoriteList]
          } else {
            // 首次加载，替换数据
            this.categories.assistant.items = favoriteList
          }
          
          this.categories.assistant.count = result.data?.total || result.total || 0
          this.hasMore = favoriteList.length === this.pageSize
          
          if (isLoadMore && favoriteList.length === 0) {
            this.hasMore = false
          }
        } else {
          uni.showToast({
            title: result.message || '获取收藏列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取收藏列表失败:', error)
        uni.showToast({
          title: '获取收藏列表失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 加载更多
    loadMore() {
      if (this.loading || !this.hasMore) return
      
      //this.page += 1
      this.getFavoriteList(true)
    },
    
    // 处理图片加载错误
    handleImageError(e) {
      // 设置默认图片
      const target = e.target
      if (target) {
        target.src = '/static/icons/default-app.png'
      }
    }
  }
}
</script>

<style scoped>
.chat-container {
  background-color: #3F3757;
}

.content-scroll {
  height: calc(100% - 80rpx);
  padding: 20rpx;
}

.top-section {
  background-color: #4A416A;
  padding: 20rpx;
  border-bottom: 1rpx solid #5A527A;
}

.search-bar {
  background-color: #5A527A;
  border-radius: 30rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  color: #D1C8EC;
  font-size: 26rpx;
}

.subscribe-btn {
  position: absolute;
  right: 20rpx;
  top: 20rpx;
  background-color: #7F6BFF;
  border-radius: 30rpx;
  padding: 10rpx 20rpx;
  display: flex;
  align-items: center;
}

.subscribe-icon {
  color: #fff;
  font-size: 24rpx;
  margin-right: 5rpx;
}

.subscribe-text {
  color: #fff;
  font-size: 24rpx;
}

.category-section {
  background-color: #4A416A;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

.category-header {
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #5A527A;
}

.category-title {
  display: flex;
  align-items: center;
}

.toggle-icon {
  color: #D1C8EC;
  font-size: 24rpx;
  margin-right: 10rpx;
}

.category-name {
  color: #D1C8EC;
  font-size: 40rpx;
}

.category-count {
  color: #D1C8EC;
  font-size: 24rpx;
}

.category-content {
  padding: 0;
}

.chat-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #5A527A;
}

.chat-item:last-child {
  border-bottom: none;
}

.item-icon {
  width: 100rpx;
  height: 100rpx;
  background-color: #5A527A;
  border-radius: 15rpx;
  margin-right: 20rpx;
  overflow: hidden;
}

.icon-image {
  width: 100%;
  height: 100%;
}

.item-info {
  flex: 1;
}

.item-title {
  color: #D1C8EC;
  font-size: 36rpx;
  margin-bottom: 10rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
}

.item-desc {
  color: #8F88A9;
  font-size: 26rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
}

.load-more {
  text-align: center;
  padding: 20rpx;
  color: #8F88A9;
  font-size: 24rpx;
}

.empty-state {
  text-align: center;
  padding: 60rpx 20rpx;
  color: #8F88A9;
  font-size: 24rpx;
}

/* 分类应用相关样式 */
.category-subsection {
  background-color: #52496D;
  border-radius: 15rpx;
  margin-bottom: 15rpx;
  overflow: hidden;
}

.category-subsection:last-child {
  margin-bottom: 0;
}

.category-subcontent {
  background-color: #52496D;
}

.category-apps-content {
  padding-left: 20rpx;
}

.category-app-item {
  margin-left: 60rpx;
  border-top: 1rpx solid #5A527A;
}
</style>
